package com.yunlan.friendscenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunlan.friendscenter.common.ErrorCode;
import com.yunlan.friendscenter.contant.UserConstant;
import com.yunlan.friendscenter.exception.BusinessException;
import com.yunlan.friendscenter.pojo.Userdata;
import com.yunlan.friendscenter.service.UserdataService;
import com.yunlan.friendscenter.mapper.UserdataMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【userdata】的数据库操作Service实现
* @createDate 2022-04-28 16:10:44
*/
@Service
@Slf4j
public class UserdataServiceImpl extends ServiceImpl<UserdataMapper, Userdata>
    implements UserdataService {

    @Autowired
    private UserdataMapper userdataMapper;

    /**
     * 密码加密盐
     */
    private final String SALT = "yunLan";


    @Override
    public Long userRegister(String userAccount, String userPassword, String checkPassword) {
        //1. 校验
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword)) {
           throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数为空") ;
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数不合法") ;
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数不合法") ;
        }

        //账户合理性校验
        String regEx = "[`~!@#$%^&*()+=|{}':;'\\[\\]<>/?~！@#￥%……&*——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(regEx).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数不合法") ;
        }

        //密码和校验码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数不合法") ;
        }

        //账号不能重复
        LambdaQueryWrapper<Userdata> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Userdata::getAvatarurl, userAccount);
        long count = userdataMapper.selectCount(lambdaQueryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.SUCCESS,"此账号以被注册") ;
        }

        //密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //数据插入
        Userdata userdata = new Userdata();
        userdata.setUseraccount(userAccount);
        userdata.setUserpassword(encryptPassword);
        int insertResult = userdataMapper.insert(userdata);
        if (insertResult == 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"内部错误") ;
        }
        return userdata.getId();
    }

    @Override
    public Userdata userLogin(String userAccount, String userPassword, HttpServletRequest request) {

        //1. 校验
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            // todo 返回异常
           throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数不合法");
        }
        if (userAccount.length() < 4) {
           throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数不合法") ;
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数不合法") ;
        }

        //账户合理性校验
        String regEx = "[`~!@#$%^&*()+=|{}':;'\\[\\]<>/?~！@#￥%……&*——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(regEx).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数不合法") ;
        }

        //2.加密验证
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //查询用户是否存在
        LambdaQueryWrapper<Userdata> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Userdata::getUseraccount, userAccount);
        lambdaQueryWrapper.eq(Userdata::getUserpassword, encryptPassword);
        Userdata userdata = userdataMapper.selectOne(lambdaQueryWrapper);
        //用户不存在
        if (userdata == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.NOT_LOGIN,"用户不存在") ;
        }

        //3.用户拖敏
        Userdata safeUserData = new Userdata();
        safeUserData =  reduceUserData(userdata);

        //4.记录用户的登录状态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, safeUserData);
        return safeUserData;
    }

    @Override
    public Page<Userdata> searchUserData(String username, HttpServletRequest request,String pagenum,String pagesize,String value) {
        if (!isAdmin(request)){
           throw new BusinessException(ErrorCode.NO_AUTH);
        }

        if (StringUtils.isAllBlank(pagenum,pagesize)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求页数为空");
        }
        QueryWrapper<Userdata> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isAllBlank(username)==false && StringUtils.isAllBlank(value)==false){
            queryWrapper.like(value,username);
        }
         System.out.println(pagenum+pagesize);
        //todo 此处可以优化
        Page<Userdata> page=new Page<>(Integer.valueOf(pagenum),Integer.valueOf(pagesize));
        Page<Userdata> pageList =  userdataMapper.selectPage(page,queryWrapper);
        System.out.println(pageList.toString());
        List<Userdata> listData = pageList.getRecords();
        List<Userdata> newListUserdata = listData.stream().map(userdata -> reduceUserData(userdata)).collect(Collectors.toList());
        pageList.setRecords(newListUserdata);
        return pageList;
    }

    @Override
    public boolean delectUserData(long id,HttpServletRequest request) {
        if (!isAdmin(request)){
          throw new BusinessException(ErrorCode.NULL_ERROR,"请求体异常");
        }
        if (id<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数错误");
        }
        if (userdataMapper.deleteById(id)!=1){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"系统错误联系开发人员");
        }

        return true;
    }

    @Override
    public int userLoginOut(HttpServletRequest request) {
        try{
            request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
            return 1;
        }catch (Exception e){
            return 0;
        }
    }

    private static boolean isAdmin(HttpServletRequest request) {
        //仅管理员可以查看
        Object user = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        Userdata userdata = (Userdata) user;
        if (userdata.getUserrole() == UserConstant.USER_Role_Admin) {
            return true;
        }
        return false;
    }

    private static Userdata reduceUserData(Userdata userdata) {
        Userdata safeUserData = new Userdata();
        safeUserData.setId(userdata.getId());
        safeUserData.setUsername(userdata.getUsername());
        safeUserData.setUseraccount(userdata.getUseraccount());
        safeUserData.setAvatarurl(userdata.getAvatarurl());
        safeUserData.setGender(userdata.getGender());
        safeUserData.setUserrole(userdata.getUserrole());
        safeUserData.setPhone(userdata.getPhone());
        safeUserData.setEmail(userdata.getEmail());
        safeUserData.setUserstatus(userdata.getUserstatus());
        safeUserData.setCreatetime(userdata.getCreatetime());
        return safeUserData;
    }
}




